class User < ActiveRecord::Base
  has_many  :emails,
            :dependent=>:delete_all
  has_one   :major_email,
            :class_name=>"Email",
            :foreign_key=>"user_id",
            :conditions=>"is_major=1"
  has_one   :face,
            :dependent=>:delete

#------shawn-----------------            
  has_many :talks, :through => :user_talks
  has_many :user_talks, :dependent => :destroy

  has_many :talkees
  has_many :invitations
#  belongs_to :invitation
#------shawn-----------------            
            
  
  validates_presence_of   :fullname,:username,:email
  validates_uniqueness_of :username,:email
  attr_accessor           :password_confirmation
  
  validates_confirmation_of  :password
  validate :password_non_blank    #need to check password at signup page

  def password
    @password
  end
  
  def password=(pwd)
    @password=pwd
    return if pwd.blank?
    create_new_salt
    self.hashed_password=User.encrypted_password(@password,self.salt)  
  end
  
  def self.authenticate(username,password)
    user=self.find_by_username(username)
    if user
      expected_password=encrypted_password(password,user.salt)
      if user.hashed_password!=expected_password
        user=nil
      end
    end
    user
  end
  
  def resethash
    string_to_hash=self.hashed_password+"GruTalk"+self.object_id.to_s+rand.to_s
    self.reset_hash=Digest::SHA1.hexdigest(string_to_hash)
    self.reset_date=Time.now
  end
  
  private
  def password_non_blank
    errors.add_to_base("Missing Password") if hashed_password.blank?
  end

  def self.encrypted_password(password,salt)
    string_to_hash=password+"GruTalk"+salt
    Digest::SHA1.hexdigest(string_to_hash)
  end
  

  
  def create_new_salt
    self.salt=self.object_id.to_s+rand.to_s
  end
  
  
end
